﻿using WeixinSB.Common;
using WeixinSB.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WeixinSB.Model;
using LYL.Common.RT.Text;
using Windows.Storage.Pickers;
using Windows.UI.ViewManagement;
using Windows.Storage;
using Windows.ApplicationModel.Activation;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
using WeixinSB.Tools;

// The Pivot Application template is documented at http://go.microsoft.com/fwlink/?LinkID=391641

namespace WeixinSB
{
    /// <summary>
    /// A page that displays details for a single item within a group.
    /// </summary>
    public sealed partial class EditPage : Page, IFileOpenPickerContinuable
    {
        private readonly NavigationHelper navigationHelper;

        private WeixinSbModel item = new WeixinSbModel();

        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();

        private readonly string headFileName = Guid.NewGuid() + ".jpg";

        private readonly string attachFileName = Guid.NewGuid() + ".jpg";

        private const string Prefix = "ms-appdata:///local/";

        const string CONTINUATIONDATA_KEY = "Type";

        public static EditPage Current;

        public EditPage()
        {
            this.InitializeComponent();
            Current = this;
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
        }

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// Gets the view model for this <see cref="Page"/>.
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public WeixinSbModel Model
        {
            get { return this.item; }
        }

        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data.
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/>.</param>
        /// <param name="e">Event data that provides an empty dictionary to be populated with
        /// serializable state.</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: Save the unique state of the page here.
        }

        #region NavigationHelper registration

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();

            item = TemplateDataST.Single;
            //补够10个评论人
            if (item != null)
            {
                if (item.CommentList != null && item.CommentList.Count > 0)
                {
                    var addCount = 10 - item.CommentList.Count;
                    for (int i = 0; i < addCount; i++)
                    {
                        item.CommentList.Add(new CommentModel());
                    }
                }
            }

            this.DefaultViewModel["Item"] = item;

            this.navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private void Head_Tapped(object sender, TappedRoutedEventArgs e)
        {
            OpenFile(ImageType.Head.ToString());
        }

        private static void OpenFile(string type)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.ContinuationData[CONTINUATIONDATA_KEY] = type;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            // Launch file open picker and caller app is suspended and may be terminated if required
            openPicker.PickSingleFileAndContinue();
        }


        /// <summary>
        /// Handle the returned files from file picker
        /// This method is triggered by ContinuationManager based on ActivationKind
        /// </summary>
        /// <param name="args">File open picker continuation activation argment. It cantains the list of files user selected with file open picker </param>
        public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            if (args.Files.Count > 0)
            {
                //OutputTextBlock.Text = "Picked photo: " + args.Files[0].Name;
                StorageFile file = args.Files[0];

                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(fileStream);
                if (args.ContinuationData.ContainsKey(CONTINUATIONDATA_KEY) 
                    && args.ContinuationData[CONTINUATIONDATA_KEY].ToString() == ImageType.Attach.ToString())
                {
                    //附件
                    attachImage.Source = bitmapImage;

                    var bytes = await BufferExtension.IRandomAccessStreamToBytes(fileStream);
                    await StorageFileEx.Create(attachFileName, bytes);

                    if (item.Attachment != null && item.Attachment.Length > 0)
                    {
                        item.Attachment[0] = Prefix + attachFileName;
                    }
                }
                else if (args.ContinuationData.ContainsKey(CONTINUATIONDATA_KEY) 
                    && args.ContinuationData[CONTINUATIONDATA_KEY].ToString() == ImageType.Head.ToString())
                {
                    //头像
                    headImage.Source = bitmapImage;

                    var bytes = await BufferExtension.IRandomAccessStreamToBytes(fileStream);

                    await StorageFileEx.Create(headFileName, bytes);

                    item.HeadUrl = Prefix + headFileName;

                }
            }
            else
            {
                //OutputTextBlock.Text = "Operation cancelled.";
            }
        }

        private void Attach_Tapped(object sender, TappedRoutedEventArgs e)
        {
            OpenFile(ImageType.Attach.ToString());
        }

        private void Template_Tapped(object sender, TappedRoutedEventArgs e)
        {
            
            var btn = sender as Button;
            if (btn != null)
            {
                var sb = btn.DataContext as WeixinSbModel;
                if (sb != null)
                {
                    switch (btn.Tag.ToString())
                    {
                        case "0":
                            sb.IphoneOpacity = 0.2;
                            sb.WpOpacity = 1.0;
                            sb.AndroidOpacity = 1.0;
                            break;
                        case "1":
                            sb.IphoneOpacity = 1.0;
                            sb.WpOpacity = 0.2;
                            sb.AndroidOpacity = 1.0;
                            break;
                        case "2":
                            sb.IphoneOpacity = 1.0;
                            sb.WpOpacity = 1.0;
                            sb.AndroidOpacity = 0.2;
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }
}